package cn.tedu._05mvcboot06.controller;

import cn.tedu._05mvcboot06.common.respose.JsonResult;
import cn.tedu._05mvcboot06.common.respose.StatusCode;
import cn.tedu._05mvcboot06.mapper.UserMapper;
import cn.tedu._05mvcboot06.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot06.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot06.pojo.entity.Article;
import cn.tedu._05mvcboot06.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Slf4j
@Api(tags = "用户文章")
@RestController
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session) {
        log.debug("userLoginDTO=" + userLoginDTO);
        UserVO userVO = userMapper.selectLoginUser(userLoginDTO.getPassword(), userLoginDTO.getUsername());
        if (userVO != null) {
            session.setAttribute("user", userVO);
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
    }
    @PostMapping("article")
    @ApiOperation(value = "发表文章")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO,@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        Article article=new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());
        userMapper.insertArticle(article);
        return JsonResult.ok();
    }
}
